#!/bin/bash
# 更新仪表盘功能 - 安装 psutil 依赖

echo "=========================================="
echo "   更新 CMDB 仪表盘功能"
echo "=========================================="
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 检查虚拟环境
if [ ! -d ".venv" ]; then
    echo "❌ 虚拟环境不存在，请先运行: bash deploy.sh"
    exit 1
fi

echo "🔧 激活虚拟环境..."
. .venv/bin/activate

echo "📦 安装 psutil 依赖..."
pip install psutil==5.* -q

echo "✅ 依赖安装完成"
echo ""

# 询问是否重启服务
read -p "是否重启后端服务以应用更改? (y/n): " restart
if [ "$restart" = "y" ] || [ "$restart" = "Y" ]; then
    echo ""
    echo "🔄 重启后端服务..."
    
    # 停止后端
    if [ -f "logs/backend.pid" ]; then
        BACKEND_PID=$(cat logs/backend.pid)
        if ps -p $BACKEND_PID > /dev/null 2>&1; then
            kill $BACKEND_PID
            echo "  停止后端 (PID: $BACKEND_PID)"
            sleep 2
        fi
    fi
    
    # 启动后端
    cd backend
    nohup daphne -b 0.0.0.0 -p 8000 backend.asgi:application > ../logs/backend.log 2>&1 &
    BACKEND_PID=$!
    echo $BACKEND_PID > ../logs/backend.pid
    cd ..
    
    echo "  后端已启动 (PID: $BACKEND_PID)"
    sleep 2
    
    # 测试API
    if curl -s http://localhost:8000/api/system-info/ > /dev/null 2>&1; then
        echo "  ✅ 系统信息API可用"
    else
        echo "  ⚠️  等待服务启动..."
        sleep 3
    fi
fi

echo ""
echo "=========================================="
echo "   ✅ 更新完成"
echo "=========================================="
echo ""
echo "📊 新功能:"
echo "  - 系统仪表盘（CPU、内存、磁盘监控）"
echo "  - 可莉3D人物（可交互）"
echo "  - 系统信息API: /api/system-info/"
echo ""
echo "🌐 访问仪表盘:"
echo "  http://localhost:8080/dashboard"
echo ""
echo "💡 测试API:"
echo "  curl http://localhost:8000/api/system-info/"
echo ""
